package com.czzhan.captcha.common.dto;

import lombok.Data;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * CaptchaDto
 *
 * @author czzhan
 * @date 2024/5/5 18:19
 */
@Data
public class CaptchaDto {

    private String ip;

    private String servletPath;

    private String date;

    private Integer count;

    public CaptchaDto(String ip, String servletPath) {
        this.ip = ip;
        this.servletPath = servletPath;
        this.date = DateFormatUtils.format(new Date(), DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern());
        count = 0;
    }

    public String getKey() {
        String key = ip + servletPath + date;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] mdBytes = md.digest(key.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : mdBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            return key;
        }
    }
}
